<!--
 * @Description: 文件切片
 * @Author: chenjiaxin
 * @Date: 2024-11-19 10:15:27
 * @LastEditTime: 2024-11-19 11:34:43
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>文件切片</title>
  </head>
  <body>
    <input type="file" id="fileInput" />
    <script>
      const fileInput = document.getElementById("fileInput");
      fileInput.addEventListener("change", (event) => {
        const file = event.target.files[0];

        console.log(file);
        // 进行文件切片处理

        const chunkSize = 1024 * 1024; // 每个片段的大小，例如1MB

        const chunks = Math.ceil(file.size / chunkSize); // 计算需要的片段数量

        const fileSilces = [];

        for (let i = 0; i < chunks; i++) {
          const start = i * chunkSize;

          const end = Math.min(file.size, start + chunkSize);

          const chunk = file.slice(start, end);

          fileSilces.push(chunk);
        }

        fileSilces.forEach((chunk, index) => {
          const formData = new FormData();
          formData.append("file", chunk);
          formData.append("chunkIndex", index);
          formData.append("totalChunks", chunks);
          formData.append("fileName", file.name);

          // fetch('/upload', {
          //   method: 'POST',
          //   body: formData
          // })
          // .then(response => response.json())
          // .then(data => {
          //   console.log(`Chunk ${index} uploaded successfully`);
          // })
          // .catch(error => {
          //   console.error(`Error uploading chunk ${index}:`, error);
          // });
        });

        setTimeout(() => {
          console.log(fileSilces);
          const reassembledBlob = new Blob(fileSilces, { type: 'application/octet-stream' });
          const url = URL.createObjectURL(reassembledBlob);
          // 创建一个下载链接
          const a = document.createElement('a');
          a.href = url;
          a.download = 'reassembled-file.jpg'; // 设置下载文件的名称
          document.body.appendChild(a);
          a.click();

          // 清理
          document.body.removeChild(a);
          URL.revokeObjectURL(url);
        }, 3000)
      });
    </script>
  </body>
</html>
